<?php
/**
 * 管理员模型类
 * User: ws
 * Date: 2018/7/20
 * Time: 14:44
 */

namespace app\admin\model;
use think\Db;
use think\Model;

class AdminUser extends Model
{
    function initialize()
    {
        parent::initialize();
    }

    function do_login($params){
        if(empty($params['username'])) {
            return FALSE;
        }
        if(empty($params['password'])) {
            return FALSE;
        }

        $admin_user = $this->where('name',$params['username'])->find();

        if(!$admin_user) {
            return FALSE;
        }
        $admin_user = $admin_user->toArray();
        if($admin_user['pass'] !== strtolower(md5($params['password']))) {
            return FALSE;
        }

        unset($admin_user['pass']);
        unset($admin_user['email']);
        unset($admin_user['phone']);


        $admin_role = Db::name('admin_role')->where('admin_role_id',$admin_user['admin_role_id'])->find();

        session('role_auth_'.$admin_user['admin_role_id'], $admin_role['role_auth'] ? json_decode($admin_role['role_auth'], true) : json_decode($admin_role['role_auth'], true));

        session('admin_user',$admin_user);
        return $admin_user;
    }


    function add($params){
        $result = $this->isUpdate(false)->allowField(true)->save($params);
        if($result){
            return 1;
        }else{
            return false;
        }
    }

    function edit($params){
        $result = $this->isUpdate(true)->allowField(true)->save($params);
        if($result){
            return true;
        }else{
            return false;
        }
    }

    // 权限
    function role()
    {
        return $this->hasOne('AdminRole', 'admin_role_id', 'admin_role_id');
    }

    /**
     * 获取列表
     * $whith_page 0不分页  1分页返回对象  2分页返回数组
     *
     */
    function get_list($where = '',$order = 'admin_user_id desc',$page_size=15,$whith_page=0,$field= '*'){
        if(!$order){ $order = 'admin_user_id desc';}
        if($whith_page == 0){
            $articles = $this->where($where)->field($field)->order($order)->limit($page_size)->select();
            return $articles;
        }
        $articles = $this->where($where)->field($field)->order($order)->paginate($page_size);
        if($whith_page == 1){
            return $articles;
        }
        $articles = $articles->toArray();
        return $articles;
    }


}